﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AmazonAssociatesAPIWCF.Amazon.ECS;
using System.ServiceModel;
using System.Configuration;

namespace AmazonAssociatesAPIWCF
{
    public class AmazonData
    {
        #region Properties
        public static string awsAccessKeyId
        {
            get
            {
                return ConfigurationManager.AppSettings["AwsAccessKeyId"];
            }
        }

        public static string awsSecretKeyId
        {
            get
            {
                return ConfigurationManager.AppSettings["AwsSecretKeyID"];
            }
        }

        public static string MyResponseGroup
        {
            get
            {
                return "Request,SalesRank,Small,Images,OfferSummary";
            }
        }

        #endregion

        #region Private methods

        private static AWSECommerceServicePortTypeClient GetClient()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.MaxReceivedMessageSize = int.MaxValue;
            AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
                binding,
                new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));

            // add authentication to the ECS client
            client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(awsAccessKeyId, awsSecretKeyId));
            return client;
        }


        #endregion

        /// <summary>
        /// Get a books by their title (ItemSearch)
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public List<AmazonStrongType> DoItemSearch(string title)
        {
            List<AmazonStrongType> myList = new List<AmazonStrongType>();
            // create a WCF Amazon ECS client
            AWSECommerceServicePortTypeClient client = GetClient();

            //prepare an ItemSearch request
            //by limiting an XML file to be parsed
            ItemSearchRequest request = new ItemSearchRequest();
            request.SearchIndex = "Books";
            request.Title = title;
            //Get all of the XML needed to be parsed
            request.ResponseGroup = new string[] { MyResponseGroup };

            ItemSearch itemSearch = new ItemSearch();
            itemSearch.Request = new ItemSearchRequest[] { request };
            itemSearch.AWSAccessKeyId = awsAccessKeyId;


            //issue the ItemSearch request
            ItemSearchResponse response = client.ItemSearch(itemSearch);
            //Add each item to a strongly typed class
            //that populates a list
            foreach (var item in response.Items[0].Item)
            {
                //If there is a null, then don't add it to the list
                try
                {
                    AmazonStrongType a = new AmazonStrongType();
                    a.ASIN = item.ASIN;
                    a.DetailPageUrl = item.DetailPageURL;
                    a.LargeProductImageUrl = item.LargeImage.URL;
                    a.Manufacturer = item.ItemAttributes.Manufacturer;
                    a.MediumProductImageUrl = item.MediumImage.URL;
                    a.ProductName = item.ItemAttributes.Title;
                    a.ProductPrice = decimal.Parse(item.OfferSummary.LowestNewPrice.FormattedPrice.Replace("$", ""));
                    a.SalesRank = int.Parse(item.SalesRank);
                    a.SmallProductImageUrl = item.SmallImage.URL;
                    myList.Add(a);
                }
                catch (Exception ex)
                {

                }
            }
            return myList;
        }

        /// <summary>
        /// Looks for similar products based on an ItemID (SimilarityLookup)
        /// </summary>
        /// <param name="ItemID"></param>
        /// <returns></returns>
        public List<AmazonStrongType> DoSimilarityLookupByID(string ItemID)
        {
            List<AmazonStrongType> myList = new List<AmazonStrongType>();
            // create a WCF Amazon ECS client
            AWSECommerceServicePortTypeClient client = GetClient();

            //Log in
            SimilarityLookup sl = new SimilarityLookup();
            sl.AWSAccessKeyId = awsAccessKeyId;

            //Get the info
            SimilarityLookupRequest request = new SimilarityLookupRequest();
            request.ItemId = new string[] { ItemID };

            //Get all the data, so the info can be parsed
            request.ResponseGroup = new string[] { MyResponseGroup };
            sl.Request = new SimilarityLookupRequest[] { request };

            SimilarityLookupResponse response = client.SimilarityLookup(sl);

            //Add each item to a strongly typed class
            //that populates a list
            foreach (var item in response.Items[0].Item)
            {
                //If there is a null, don't add it to the list
                try
                {
                    AmazonStrongType a = new AmazonStrongType();
                    a.ASIN = item.ASIN;
                    a.DetailPageUrl = item.DetailPageURL;
                    a.LargeProductImageUrl = item.LargeImage.URL;
                    a.Manufacturer = item.ItemAttributes.Manufacturer;
                    a.MediumProductImageUrl = item.MediumImage.URL;
                    a.ProductName = item.ItemAttributes.Title;
                    a.ProductPrice = decimal.Parse(item.OfferSummary.LowestNewPrice.FormattedPrice.Replace("$", ""));
                    a.SalesRank = int.Parse(item.SalesRank);
                    a.SmallProductImageUrl = item.SmallImage.URL;
                    myList.Add(a);
                }
                catch (Exception ex)
                {

                }
            }
            return myList;
        }

        /// <summary>
        /// Get an item by its ID (ItemLookup)
        /// </summary>
        /// <param name="ItemID"></param>
        /// <returns></returns>
        public List<AmazonStrongType> DoItemLookup(string ItemID)
        {
            List<AmazonStrongType> myList = new List<AmazonStrongType>();
            // create a WCF Amazon ECS client
            AWSECommerceServicePortTypeClient client = GetClient();
            ItemLookupRequest request = new ItemLookupRequest();
            request.ItemId = new string[] { ItemID };
            request.ResponseGroup = new string[] { MyResponseGroup };
            ItemLookup il = new ItemLookup();
            il.AWSAccessKeyId = awsAccessKeyId;
            il.Request = new ItemLookupRequest[] { request };
            ItemLookupResponse response = client.ItemLookup(il);

            //Add each item to a strongly typed class
            //that populates a list
            foreach (var item in response.Items[0].Item)
            {
                try
                {
                    //If there is a null, then don't add it to the list
                    AmazonStrongType a = new AmazonStrongType();
                    a.ASIN = item.ASIN;
                    a.DetailPageUrl = item.DetailPageURL;
                    a.LargeProductImageUrl = item.LargeImage.URL;
                    a.Manufacturer = item.ItemAttributes.Manufacturer;
                    a.MediumProductImageUrl = item.MediumImage.URL;
                    a.ProductName = item.ItemAttributes.Title;
                    a.ProductPrice = decimal.Parse(item.OfferSummary.LowestNewPrice.FormattedPrice.Replace("$", ""));
                    a.SalesRank = int.Parse(item.SalesRank);
                    a.SmallProductImageUrl = item.SmallImage.URL;
                    myList.Add(a);
                }
                catch (Exception ex)
                {

                }
            }
            return myList;
        }
    }
}
